/*
 *    Copyright (c) 2018-2025, proj All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the proj developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: proj
 */

package com.ykht.proj.coupon.controller.b;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.binarywang.wxpay.bean.entpay.EntPayQueryResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.pig4cloud.plugin.idempotent.annotation.Idempotent;
import com.ykht.proj.admin.api.entity.SysUser;
import com.ykht.proj.admin.api.feign.RemoteUserService;
import com.ykht.proj.admin.api.vo.UserVO;
import com.ykht.proj.common.core.util.R;
import com.ykht.proj.common.security.util.SecurityUtils;
import com.ykht.proj.coupon.Enum.UserTypeEnum;
import com.ykht.proj.coupon.service.FxWaiterExtService;
import com.ykht.proj.coupon.service.FxWithdrawalService;
import com.ykht.proj.coupon.vo.FxWithdrawalVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 提现记录表
 *
 * @author proj code generator
 * @date 2021-02-01 19:00:17
 */
@RestController
@AllArgsConstructor
@RequestMapping("b/fxwithdrawal")
@Api(value = "b/fxwithdrawal", tags = "提现记录表管理")
@Slf4j
public class BxWithdrawalController {

	private final FxWithdrawalService fxWithdrawalService;
	/**
	 * 服务员 服务
	 */
	private final FxWaiterExtService fxWaiterExtService;
	/**
	 * 用户 服务 Api
	 */
	private final RemoteUserService remoteUserService;

	/**
	 * 获取服务员可提现金额和已提现金额
	 *
	 * @param fxWithdrawalVo
	 * @return
	 */
	@ApiOperation(value = "获取服务员可提现金额和已提现金额", notes = "获取服务员可提现金额和已提现金额")
	@GetMapping("/getBalanceWithdrawal")
	public R<FxWithdrawalVo> getBalanceWithdrawal(FxWithdrawalVo fxWithdrawalVo) {
		List<Long> waiterIdList = fxWaiterExtService.getWaiterIdList();
		fxWithdrawalVo.setWaiterIdList(waiterIdList);
		FxWithdrawalVo fxWithdrawalVoIPage = fxWithdrawalService.getWaiterWithdrawalCount(fxWithdrawalVo);
		if (fxWithdrawalVoIPage == null) {
			fxWithdrawalVoIPage = new FxWithdrawalVo();
		}
		fxWithdrawalVoIPage.setSureWithdrawalMoney(fxWithdrawalVoIPage.getCumulativeMoney().subtract(fxWithdrawalVoIPage.getCumulativeWithdrawalMoney()));
		return R.ok(fxWithdrawalVoIPage);
	}


	/**
	 * 服务员提现
	 *
	 * @param fxWithdrawalVo
	 * @return
	 * @Inner(false)
	 * @Inner(value = false)
	 */
	@ApiOperation(value = "服务员提现", notes = "服务员提现")
	@GetMapping("/getWaiterWithdrawal")
	@Idempotent(key = "#fxWithdrawalVo.money", expireTime = 1, info = "请勿重复点击")
	public R getWaiterWithdrawal(FxWithdrawalVo fxWithdrawalVo) {

		log.info("服务员提现：{}", JSONUtil.toJsonStr(fxWithdrawalVo));
		try {
			Integer userType = SecurityUtils.getUser().getUserType();
			if (!UserTypeEnum.WAITER.getValue().equals(userType)) {
				return R.failed("只能服务员提现");
			}
			UserVO user = remoteUserService.getByIdUser(SecurityUtils.getUserId());
			if (null == user.getPhone()) {
				return R.failed("提现必须授权手机号");
			}
			if (new BigDecimal("5000").compareTo(fxWithdrawalVo.getMoney()) == -1
					|| fxWithdrawalVo.getMoney().compareTo(new BigDecimal("1")) == -1) {
				return R.failed("提现不能大于5000元和少于1元");
			}
			return fxWithdrawalService.getWaiterWithdrawal(fxWithdrawalVo);
		} catch (RuntimeException e) {
			e.printStackTrace();
			return R.failed(e.getMessage());
		} catch (WxPayException e) {
			e.printStackTrace();
			return R.failed("请稍后再提现，商家正在马不停蹄的充值中...");
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed("提现失败");
		}
	}
//	@ApiOperation(value = "查询企业付款到零钱的结果")
//	@GetMapping("/testpay")
//	@Inner(false)
//	public R testpay(String batchNumber) throws WxPayException {
//		return R.ok(this.entPay("oZv-S4uM0Mr6UmcTJfmdbkgFWpjI",System.currentTimeMillis()+"",BigDecimal.valueOf(1)));
//	}
//	@Resource
//	private WxPayService wxService;
//	@Resource
//	private WxPayProperties properties;
//	public EntPayResult entPay(String openid, String batchNumber, BigDecimal money) throws WxPayException {
//		System.out.println(properties.getAppId());
//		System.out.println(properties.getMchAppid());
//		// 企业付款到零钱
//		EntPayRequest entPay = new EntPayRequest();
//		entPay.setMchAppid("wxd45827cc3ced6125");
//		entPay.setMchId("");
//		entPay.setDeviceInfo("");//
//		entPay.setPartnerTradeNo(batchNumber);
////		entPay.setOpenid("oZv-S4qfEHHeKu5VUKeUfjEbE98o");
//		entPay.setOpenid(openid);
//		entPay.setCheckName("NO_CHECK");//
//		entPay.setReUserName("");
//		entPay.setAmount(money.multiply(new BigDecimal("100")).intValue());
//		entPay.setDescription("吃哪网佣金提现");//
//		entPay.setSpbillCreateIp("222.128.29.234");//
//		EntPayResult entPayResult = wxService.getEntPayService().entPay(entPay);
//		System.out.println(JSONUtil.toJsonStr(entPayResult));
//		return entPayResult;
//	}
//


	/**
	 * <pre>
	 * 查询企业付款API
	 * 用于商户的企业付款操作进行结果查询，返回付款操作详细结果。
	 * 文档详见:https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_3
	 * 接口链接：https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo
	 * </pre>
	 *
	 * @param batchNumber 商户订单号
	 */
	@ApiOperation(value = "查询企业付款到零钱的结果")
	@GetMapping("/queryEntPay")
	public R<EntPayQueryResult> queryEntPay(String batchNumber) throws WxPayException {
		EntPayQueryResult entPayQueryResult = fxWithdrawalService.queryEntPay(batchNumber);
		return R.ok(entPayQueryResult);
	}

	/**
	 * 获取服务员提现记录
	 *
	 * @param page           分页对象
	 * @param fxWithdrawalVo
	 * @return
	 */
	@ApiOperation(value = "获取服务员提现记录", notes = "获取服务员提现记录")
	@GetMapping("/getWaiterWithdrawalListPage")
	public R<IPage<FxWithdrawalVo>> getWaiterWithdrawalListPage(Page page, FxWithdrawalVo fxWithdrawalVo) {
		log.info("获取服务员提现记录分页:{}+查询:{}", page, fxWithdrawalVo);
		fxWithdrawalVo.setWaiterIdList(fxWaiterExtService.getWaiterIdList());
		IPage<FxWithdrawalVo> fxWithdrawalVoIPage = fxWithdrawalService.getWaiterWithdrawalListPage(page, fxWithdrawalVo);
		return R.ok(fxWithdrawalVoIPage);
	}

}
